﻿using System;
using System.Collections.Generic;
using NoteHelper.IBusiness;
using NoteHelper.Model;
using System.ComponentModel.DataAnnotations;

namespace NoteHelper.Business.IbatisImpl
{
    public class ArticleTypeManagerImpl:ManagerBase<ArticleType>,IArticleTypeManager
    {
        public ArticleTypeManagerImpl()
        {
	    }

        public IList<ArticleType> SaveIfNotExists(List<string> attributeList)
        {
            var targetList = new List<ArticleType>();
            foreach (string name in attributeList)
            {
                var entity = GetEntityByChName(name);
                if (entity == null)
                {
                    entity = new ArticleType {ChName = name};
                    Add(entity);
                }
                targetList.Add(entity);
            }
            return targetList;
        }

        public ArticleType SaveIfNotExists(string typeName)
        {
            var entity = GetEntityByChName(typeName);
            if (entity == null)
            {
                entity = new ArticleType();
                entity.ChName = typeName;
                entity.ObjectID = (int)base.Add(entity);
            }
            return entity;
        }

        public override object Add(ArticleType entity)
        {
            var exists = GetEntityByChName(entity.ChName);
            if (exists != null)
                throw new ValidationException(string.Format("[{0}]已经存在，请不要重复添加", entity.ChName));

            return base.Add(entity);
        }

        private ArticleType GetEntityByChName(string name)
        {
            LogRuntimeSql("GetArticleTypeByChName", name);
            return Mapper.QueryForObject("GetArticleTypeByChName", name) as ArticleType;
        }
    }
}
